import { Component } from 'react'
import { View, Text, Image, Editor, RichText } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './index.scss'
import '../images/public/style.css'

//公共组件
import LgNavCustomBar from '../../components/navCustomBar'
import LgButton from '../../components/button'
//个人组件
import PrPopCheck from '../components/personal/popCheck'
//工具
import { getStorage, getBrowserController, getNet } from '../../components/utils'
import MyUtils from '../components/personal/utils'
import getInfo from '../utils/getInfo'
import { allfileIcon, codeType } from '../utils/Lib'
// import wxSdk from '../utils/wxSdk'
import { getWxSDKParams } from "../../components/utils";
//api
import {
  API_getReadDetail,//发布者查看已发布公告详情
  API_getNoReadDetail, //发布者查看未发布公告详情
  API_getEditDetail,//获取需要编辑的公告的信息
  API_getReceiverGroup,//获取接收者的分组信息
  API_getReceiverInfoByPage,//条件分页获取接收者读取信息
  API_urgeRead,//催读
} from '../../../network/servers'
import { transmitUrlToVisit } from "../../../network/proxy"
//type
import { imgATTObject, IndexState } from './type'

if (process.env.TARO_ENV === 'weapp') {
  var app = Taro.getApp().$app
} else if (process.env.TARO_ENV === 'h5') {
  // var storage = getStorage()
  if (getInfo.getEnv() === "weapp") {
    var wx = require('weixin-js-sdk')
  }
}

var browserController = getBrowserController()
var net = getNet()
const storage = getStorage()

export default class Index extends Component<any, IndexState> {
  constructor(props) {
    super(props)
    this.state = {
      isPopCheckOpen: false,
      status: 0,
      pageNumArr: [1, 1, 1, 1, 1, 1, 1, 1]
    }
    this.popCheck_open = this.popCheck_open.bind(this)
    this.popCheck_cancel = this.popCheck_cancel.bind(this)
    this.popCheck_confirm = this.popCheck_confirm.bind(this)
    this.onChangeStatus = this.onChangeStatus.bind(this)
    this.getMoreReceiver = this.getMoreReceiver.bind(this)
  }

  componentWillMount() {
    if (process.env.TARO_ENV === "h5" && getInfo.getEnv() == "weapp") {
      this.initWxSdk()
    }
    this.getFromRoute()
  }

  componentDidMount() { }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }
  //路由==============================
  getFromRoute() {
    let toNoticeDetail = MyUtils.getStorage("toNoticeDetail")
    console.log("global-toNoticeDetail", toNoticeDetail)
    let noticeStatus = toNoticeDetail.noticeData.status
    let noticeId = toNoticeDetail.noticeData.noticeId
    // let taskReleaseId = toNoticeDetail.noticeData.taskReleaseId//定时信息才有这个id
    let timeType = toNoticeDetail.noticeData.timeType
    console.log(timeType)
    this.setState({
      noticeId: noticeId,
      noticeStatus: noticeStatus,
      timeType
      // taskReleaseId:taskReleaseId
    })
    if (noticeStatus == 0) {//未发布
      this.api_getEditDetail(noticeId)
    } else {//已发布
      this.api_getReadDetail(noticeId)
      this.api_getReceiverGroup(noticeId).then(res => {
        console.log(res)
        this.setState({
          receiverGroup: res
        }, () => {
          if (timeType == 1) {

          } else {
            this.getReceiverInfo()
          }
        })
      })
    }
  }

  getReceiverInfo() {
    console.log(this.state.receiverGroup)
    if (this.state.receiverGroup == undefined) {
      return
    }
    let receiverGroup =  this.state.receiverGroup[0]
    let noticeId = this.state.noticeId
    let parentId = receiverGroup.parentId
    let status = this.state.status
    let groupId = receiverGroup.groupId
    let pageSize = 12
    console.log(receiverGroup)
    // if (receiverGroup?.teachers && receiverGroup?.teachers.length != 0) {//老师
      // let pageNum = pageNumArr[0] || 1
      this.api_getReceiverInfoByPage(noticeId, parentId, status, '', 1, pageSize).then(res => {
        this.setState({
          persons: res
        })
      })
  
  }

  getReceiverInfoByType(receiverType) {//只更新一类接收者
    console.log(this.state.receiverGroup)
    let receiverGroup = this.state.receiverGroup[0]
    let noticeId = this.state.noticeId
    let parentId = receiverGroup.parentId
    let status = this.state.status
    let groupId = receiverGroup.groupId
    let pageNumArr = this.state.pageNumArr
    console.log(pageNumArr)
    let pageNum = pageNumArr[receiverType - 1]
    this.api_getReceiverInfoByPage(noticeId, parentId, status, '', pageNum, 12).then(res => {
      console.log(res)
      if (pageNum == 1) {//如果是第一页就相当于是重置了
        this.setState({ persons: res })
        // if (receiverType == 1) {
        //   this.setState({ teachers: res })
        // } else if (receiverType == 2) {
        //   this.setState({ students: res })
        // } else if (receiverType == 3) {
        //   this.setState({ departments: res })
        // } else if (receiverType == 4) {
        //   this.setState({ identities: res })
        // } else if (receiverType == 5) {
        //   this.setState({ persons: res })
        // } else if (receiverType == 6) {
        //   this.setState({ parents: res })
        // } else if (receiverType == 7) {
        //   this.setState({ grades: res })
        // } else if (receiverType == 8) {
        //   this.setState({ classes: res })
        // }
      } else {
        if (!res || res.length == 0) {//没有更多了
          pageNum = pageNum - 1
          if (pageNum == 0) { pageNum = 1 }
          pageNumArr[receiverType - 1] = pageNum
          this.setState({
            pageNumArr: pageNumArr
          })
          Taro.showToast({ title: "已加载全部内容", icon: "none", duration: 2000 })
        } else {
            let persons = this.state.persons
            persons = persons?.concat(res)
            console.log("新的个人列表", persons)
            this.setState({ persons })
          // if (receiverType == 1) {
          //   let teachers = this.state.teachers
          //   teachers = teachers?.concat(res)
          //   console.log("新的教师列表", teachers)
          //   this.setState({ teachers })
          // } else if (receiverType == 2) {
          //   let students = this.state.students
          //   students = students?.concat(res)
          //   console.log("新的学生列表", students)
          //   this.setState({ students })
          // } else if (receiverType == 3) {
          //   let departments = this.state.departments
          //   departments = departments?.concat(res)
          //   console.log("新的部门列表", departments)
          //   this.setState({ departments })
          // } else if (receiverType == 4) {
          //   let identities = this.state.identities
          //   identities = identities?.concat(res)
          //   console.log("新的管理员列表", identities)
          //   this.setState({ identities })
          // } else if (receiverType == 5) {
          //   let persons = this.state.persons
          //   persons = persons?.concat(res)
          //   console.log("新的个人列表", persons)
          //   this.setState({ persons })
          // } else if (receiverType == 6) {
          //   let parents = this.state.parents
          //   parents = parents?.concat(res)
          //   console.log("新的家长列表", parents)
          //   this.setState({ parents })
          // } else if (receiverType == 7) {
          //   let grades = this.state.grades
          //   grades = grades?.concat(res)
          //   console.log("新的年级列表", grades)
          //   this.setState({ grades })
          // } else if (receiverType == 8) {
          //   let classes = this.state.classes
          //   classes = classes?.concat(res)
          //   console.log("新的班级列表", classes)
          //   this.setState({ classes })
          // }
        }
      }
    })
  }

  handleData(data) {
    let attachments = data.attachments
    let imageSuffix = ["png", "jpg", "jpeg"]
    let fileSuffix = ["doc", "pdf", "docx", "ppt", "pptx", "xls", "xlsx", "txt", "epub", 'apk', 'mp4', 'mp3', 'zip', 'm4a']
    let imgATTArr: imgATTObject[] = []
    let fileATTArr: imgATTObject[] = []
    console.log("attachments", attachments)
    attachments?.map(item => {
      let suffix = MyUtils.getSuffix(item.name)
      if (imageSuffix.indexOf(suffix) != -1) {//图片
        let itemImg = { ...item }
        if (process.env.TARO_ENV === "weapp" || getInfo.getEnv() === "weapp") {
          itemImg.url = this.replaceHost(itemImg.url)
        }
        // this.replaceHost(itemImg.url)
        imgATTArr.push(itemImg)
        // imgATTArr.push(item)
      } else if (fileSuffix.indexOf(suffix) != -1) {//文件
        fileATTArr.push(item)
      } else {//未知文件
        console.log("读取到未知后缀文件", item)
        fileATTArr.push(item)
      }
    })
    console.log("imgATTArr", imgATTArr)
    console.log("fileATTArr", fileATTArr)

    // setTimeout(() => {
    //   this.editorInit(data.content)
    // }, 500);

    this.setState({
      noticeData: data,
      imgATTArr,
      fileATTArr
    })
  }

  //网络请求=============================
  /**获取未发布的通知详情 */
  api_getEditDetail(noticeId) {
    let header = {
      "Authorization": getInfo.getToken()
    }
    API_getEditDetail({ noticeId }, header).then(res => {
      console.log("api-获取未发布的通知详情", res)
      if (res.code == 200) {
        this.handleData(res.data)
      } else {
        Taro.showToast({
          title: codeType[res.code],
          icon: "none",
          duration: 2000
        })
      }
    })
  }

  /**获取已发布的通知详情 */
  api_getReadDetail(noticeId) {
    let params: { noticeId: string, taskReleaseId?: string, eduId?: string } = {
      noticeId,
      // schoolId:getInfo.getSchoolId()
      eduId: getInfo.getSchoolId()
    }
    let header = {
      "Authorization": getInfo.getToken()
    }
    API_getReadDetail(params, header).then(res => {
      console.log("api-获取已发布的通知详情", res)
      if (res.code == 200) {
        this.handleData(res.data)
      } else {
        Taro.showToast({
          title: codeType[res.code],
          icon: "none",
          duration: 2000
        })
      }
    })
  }

  /**获取接收者的分组信息 */
  api_getReceiverGroup(noticeId) {
    return new Promise<any>((resolve, reject) => {
      let params = {
        noticeId: noticeId,
        // eduId:getInfo.getSchoolId()
      }
      let header = {
        "Authorization": getInfo.getToken()
      }
      API_getReceiverGroup(params, header).then(res => {
        console.log("api-获取接收者的分组信息", res, "\nparams:", params)
        if (res.code == 200) {
          resolve(res.data)
        }
      })
    })
  }

  /**
   * 条件分页获取接受者读取信息
   * @param noticeId 公告ID
   * @param status 读取状态：0/未读；1/已读
   * @param receiverType 自定义接收者类型：1/老师；2/学生；3/部门；4/身份；5/个人；6/家长。为空表示全部
   * @param pageNum 当前页
   * @param pageSize 每页条数
   */
  api_getReceiverInfoByPage(noticeId, parentId, readStatus, groupId, pageNum, pageSize) {
    return new Promise<any>((resolve, reject) => {
      let params = {
        noticeId: noticeId,
        parentId: parentId,
        readStatus: readStatus,
        // groupId: groupId,
        // eduId: getInfo.getSchoolId()
      }
      let header = {
        "Authorization": getInfo.getToken()
      }
      API_getReceiverInfoByPage(params, pageNum, pageSize, header).then(res => {
        // console.log("api-条件分页获取接受者读取信息",res)
        if (res.code == 200) {
          resolve(res.data)
        }
      })
    })
  }

  /**催读 */
  api_urgeRead() {
    Taro.showLoading({ title: '加载中' })
    let noticeId = this.state.noticeId
    let params = {
      noticeId: noticeId,
      schoolId: getInfo.getSchoolId()
    }
    let header = {
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": getInfo.getToken()
    }
    API_urgeRead(params, header).then(res => {
      console.log("api-催读", res)
      Taro.hideLoading()
      if (res.code == 200) {
        setTimeout(function () {
          Taro.showToast({ title: "已催读", icon: "success", duration: 2000 })
        }, 200)
      } else {
        setTimeout(function () {
          Taro.showToast({ title: res.msg, icon: "none", duration: 2000 })
        }, 200)
      }
    })
  }
  //WXsdk注册==========================
  async initWxSdk() {
    const params = await getWxSDKParams(['chooseImage', 'previewImage'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('WxSdk ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log("wxSdk验证失败", res)
    });
  }
  //图片==============================
  showpic(picPath, picPathArr) {//展示图片
    console.log(picPathArr)
    let arr = picPathArr.map(item => {
      return `${MyUtils.getStorage("userInfo", true).baseUrl}edu-office-platform${item.url}`
    })
    MyUtils.previewPic(picPath, arr)
  }
  //文件==========================
  downloadFile(item, index) {//下载文件
    console.log("下载文件", item)
    let fileATTArr = this.state.fileATTArr
    if (!fileATTArr) { return }

    let url = item.url
    if (process.env.TARO_ENV === 'h5') {
      if (getInfo.getEnv() === "weapp") {
        url = this.replaceHost(url)
      }
    } else {//微信小程序
      url = transmitUrlToVisit(this.replaceHost(url))
      console.log("文件下载路径:", item.url, "\n文件代理下载路径:", url)
    }

    if (getInfo.getEnv() === "weapp") {
      this.previewFile(url)
      return
    }

    net.downloadFile({
      url: url,
      fileName: item.name,
      onProgress: process => {
        console.log(`process`, process)
      },
      onSuccess: path => {
        if (getInfo.getEnv() === "weapp") {//小程序嵌入h5
          MyUtils.setStorage("filePath-" + item.attachmentId, path)
        } else {
          storage.set("filePath-" + item.attachmentId, path)
        }
        if (!fileATTArr) { return }
        fileATTArr[index].preView = true
        this.setState({
          fileATTArr
        })
      }
    })
  }

  replaceHost(url) {//替换外网IP或域名
    let baseUrl = MyUtils.getStorage("baseUrl220", true)
    console.log("baseUrl", baseUrl)
    if (!baseUrl) {
      return url
    }
    let hostOfBaseUrl: any = MyUtils.parseUrl(baseUrl)
    let newUrl = MyUtils.replaceHostOfUrl(url, hostOfBaseUrl.host, hostOfBaseUrl.port)
    return newUrl
  }

  previewFile(path) {
    console.log("下载预览路径-weapp", path)
    let suffix = MyUtils.getSuffix(path)
    try {
      browserController.openFileForWebview(wx, { fileUrl: path, fileType: suffix })
    } catch (err) {
      Taro.showToast({ title: err, icon: 'none' })
    }
  }


  fileReader(item, index) {//文件预览
    console.log("文件预览")
    let fileATTArr = this.state.fileATTArr
    if (!fileATTArr) return
    let path = ""
    if (getInfo.getEnv() === "weapp") {
      this.downloadFile(item, index)
      return
    }

    if (getInfo.getEnv() === "weapp") {//小程序嵌入H5
      path = MyUtils.getStorage("filePath-" + item.attachmentId)
    } else {
      path = storage.get("filePath-" + item.attachmentId)
    }

    if (!path) {
      Taro.showToast({
        title: "查找不到当前文件,请重新下载",
        icon: 'none',
        duration: 2000
      })
      fileATTArr[index].preView = false
      this.setState({
        fileATTArr
      })
    } else {
      console.log("预览地址", path)
      if (process.env.TARO_ENV === "h5" && getInfo.getEnv() === "weapp") {
        let suffix = MyUtils.getSuffix(path)
        let imageLib = ["img", "jpg", "jpeg"]
        if (imageLib.includes(suffix)) {
          // wxSdk.preViewImage(path)
          wx.previewImage({
            current: path, // 当前显示图片的 http 链接
            urls: [path] // 需要预览的图片 http 链接列表
          });
        } else {
          try {
            browserController.openFileForWebview(wx, { fileUrl: path, fileType: suffix })
          } catch (err) {
            Taro.showToast({ title: err, icon: 'none' })
          }
        }
      } else {
        browserController.openFileReader(path)/* 预览本地文件，目前仅支持doc、docx、ppt、pptx、xls、xlsx、pdf、txt、epub */
      }
    }
  }
  hasFile(attachmentId) {//判断是否存储了当前文件信息
    let path = ""
    if (getInfo.getEnv() === "weapp") {
      path = MyUtils.getStorage('filePath-' + attachmentId)
    } else {
      path = storage.get('filePath-' + attachmentId)
    }
    if (!path) {
      return false
    } else {
      return true
    }
  }
  //富文本编辑器=============================================
  // editorReady = e => {
  //   console.log("初始化",e)
  //   let that = this
  //   Taro.createSelectorQuery().select('#editor').context((res) => {
  //     console.log("rwwwww",res)
  //     that.editorCtx = res.context
  //   }).exec()
  // }
  // editorInit(htmlStr,num=6) {//富文本编辑器
  //   if(this.editorCtx){
  //     this.editorCtx.setContents({
  //       html:htmlStr
  //     })
  //   }else{
  //     if(num > 0){
  //       console.log("富文本内容初始化失败，实例未获取，重新初始化")
  //       setTimeout(() => {
  //         this.editorInit(htmlStr, num-1)
  //       }, 500);
  //     }else{
  //       console.log("富文本内容初始化失败，实例未获取")
  //     }
  //   }
  // }
  // editorCtx
  // editorInput(e){
  //   console.log("富文本内容改变",e)
  //   console.log("this",this)
  //   console.log("editorCtx",this.editorCtx)
  //   this.setState({
  //     contentValue:e.detail.html
  //   })
  // }
  //===========弹窗==================
  popCheck_cancel() {//关闭弹窗
    this.setState({
      isPopCheckOpen: false
    })
  }
  popCheck_open() {//打开弹窗
    this.setState({
      isPopCheckOpen: true
    })
  }
  popCheck_confirm() {//确定
    this.api_urgeRead()//点击催读
    this.setState({
      isPopCheckOpen: false
    })
  }
  onChangeStatus(newStatus) {//改变读取状态
    let status = this.state.status
    if (newStatus != status) {
      this.setState({
        status: newStatus,
        pageNumArr: [1, 1, 1, 1, 1, 1, 1, 1]//重置页数
      }, () => {
        this.getReceiverInfo()
      })
    }
  }
  getMoreReceiver(receiverType) {//获取更多接收者信息,receiverType:1/老师；2/学生；3/部门；4/身份；5/个人；6/家长
    let pageNumArr = this.state.pageNumArr
    console.log("原来的页数", pageNumArr)
    pageNumArr[receiverType - 1]++
    this.setState({
      pageNumArr
    }, () => {
      console.log("新的页数", this.state.pageNumArr)
      // this.getReceiverInfo()
      this.getReceiverInfoByType(receiverType)
    })
  }
  //获取信息=================================
  // getToken(){//token获取
  //   if(process.env.TARO_ENV === 'weapp'){
  //     return app.globalData.Token
  //   }else if(process.env.TARO_ENV === 'h5'){
  //     let token = storage.get("token")
  //     if(!token){
  //       let urlToken = MyUtils.getQueryVariable("lg_tk")
  //       return urlToken
  //     }else{
  //       return storage.get("token")
  //     }
  //   }else{
  //     console.log("未配置端,Token获取失败")
  //     return ""
  //   }
  // }
  //=================================
  render() {
    console.log(MyUtils.getStorage("userInfo", true))
    let noticeData = this.state.noticeData
    let timeType = this.state.timeType
    // let taskReleaseId = this.state.taskReleaseId
    // console.log("noticeData",noticeData)
    let imgATTArr = this.state.imgATTArr
    let fileATTArr = this.state.fileATTArr
    let isPopCheckOpen = this.state.isPopCheckOpen
    let status = this.state.status
    // let content = MyUtils.getPlainText(noticeData?.content)
    let teachers = this.state.teachers || [],
      students = this.state.students || [],
      departments = this.state.departments || [],
      identities = this.state.identities || [],
      persons = this.state.persons || [],
      parents = this.state.parents || [],
      grades = this.state.grades || [],
      classes = this.state.classes || []

    let env = getInfo.getEnv()
    return (
      <View className='noticeDetail'>
        {
          env === "weapp" ? "" :
            <LgNavCustomBar
              mainTitle={'通知详情'}
              needMainIcon={process.env.TARO_ENV === "h5" ? true : false}
              needBackIcon={true}
              isTitlePositionLeft={true}
              mainTitleBold={false}
            ></LgNavCustomBar>
        }
        <View className='scroll'>
          <View className='tophalf_title_box'>
            <View className='tophalf_title'>
              <View className='title'>{noticeData?.title}</View>
              <View className='notice_info'>
                <Text className='notice_info_item'>{noticeData?.status == -1 ? "未发布" : noticeData?.releaseTime}</Text>
                <Text className='dividing_line'>|</Text>
                <Text className='notice_info_item'>{noticeData?.userName}</Text>
                {/* <Text className='dividing_line'>|</Text>
                <Text className='notice_info_item'>{noticeData?.readNum}(已阅)</Text> */}
              </View>
            </View>

            <View className='notice_main_box'>
              <View className='notice_main'>
                {/* {
                  process.env.TARO_ENV === "weapp"?
                  <RichText className='notice_text'
                    style={{wordBreak:"break-all"}}
                    nodes={noticeData?.content}
                  >
                  </RichText>
                  :
                  <Text className='notice_text' selectable={true}>
                    {MyUtils.getPlainText(noticeData?.content)}
                  </Text>
                } */}
                <RichText className='notice_text'
                  style={{ wordBreak: "break-all" }}
                  nodes={noticeData?.content}
                >
                </RichText>

                <View className='notice_img_list'>
                  {
                    imgATTArr?.map((item, index) => {
                      return (
                        <Image className='img_item' key={"img" + item.attachmentId}
                          src={`${MyUtils.getStorage("userInfo", true).baseUrl}edu-office-platform${item.url}`}
                          mode="aspectFill"
                          onClick={() => this.showpic(`${MyUtils.getStorage("userInfo", true).baseUrl}edu-office-platform${item.url}`, imgATTArr)}
                        ></Image>
                      )
                    })
                  }
                </View>

                <View className='DOCREC_list'>
                  {
                    fileATTArr?.map((item, index) => {
                      let svgIcon = allfileIcon[MyUtils.getSuffix(item.name)]
                      let hasFile = this.hasFile(item.attachmentId)
                      return (
                        <View className='item' key={"file" + item.attachmentId}>
                          <View className={`icon_file ${svgIcon ? "prIcon_" + svgIcon : "prIcon_0a01101"}`}></View>
                          <View className='doc_name'>{item.name}</View>
                          {
                            hasFile || item.preView ? <View className='check' onClick={() => this.fileReader(item, index)}>查看</View> :
                              <View className='icon icon_download' onClick={() => this.downloadFile(item, index)}></View>
                          }
                        </View>
                      )
                    })
                  }
                </View>

              </View>
            </View>
          </View>

        </View>

        {
          timeType == 0 || timeType == undefined ?
            (
              noticeData?.status != -1 ?
                <View className='noticeDetail_btnBox'>
                  <View className='text'>
                    <Text style={{ color: "#009900" }}>已读{noticeData?.readCount}人</Text>
                    <Text style={{ color: "#999999" }}>/未读{noticeData?.unReadCount}人</Text>
                  </View>
                  <LgButton className='btn_detail' type='C' onClick={this.popCheck_open}>详情</LgButton>
                </View>
                : ""
            )
            : ""
        }

        <PrPopCheck
          data={{ teachers, students, departments, identities, persons, parents, grades, classes }}
          status={status}
          isOpen={isPopCheckOpen}
          cancel={this.popCheck_cancel}
          confirm={this.popCheck_confirm}
          number={{ readNum: noticeData?.readCount, unReadNum: noticeData?.unReadCount }}
          onChangeStatus={this.onChangeStatus}
          getMore={this.getMoreReceiver}
        ></PrPopCheck>
      </View>
    )
  }
}
